#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, Float, Boolean, String, Unicode, UnicodeText, \
    DateTime
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""collect collection has
    userid:         收藏用户id（int）
    authorid:       游记作者id（int）
    cityid:         城市id（int）
    journeyid:      游记id（int）
"""


class CollectItem(object):
    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['authorid'] = self.authorid
        res['cityid'] = self.cityid
        res['journeyid'] = self.journeyid
        return res

    def __repr__(self):
        return "%d" % (self.userid)


collect_item_table = Table(
    'collect_base', metadata,
    Column('id', Integer, primary_key=True),
    Column('userid', Integer, index=True, nullable=False),
    Column('authorid', Integer, index=True, nullable=False),
    Column('cityid', Integer, index=True, nullable=False),
    Column('journeyid', Integer, index=True, nullable=False))


def create_collect_item_table_if_not_exist():
    metadata.create_all(engine)
    mapper(CollectItem, collect_item_table)


def add_collect_item(p_item):
    item = CollectItem()
    item.userid = p_item['userid']
    item.authorid = p_item['authorid']
    item.cityid = p_item['cityid']
    item.journeyid = p_item['journeyid']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


def get_collect_by_userid(p_userid):
    try:
        session = Session()
        query = session.query(CollectItem)
        item = query(CollectItem).filter_by(userid=p_userid).first()
        res = {
            'userid': item.userid,
            'authorid': item.authorid,
            'cityid': item.cityid,
            'journeyid': item.journeyid
        }
        return res
    except Exception, e:
        return None
    finally:
        session.close()
        # session.remove()


if __name__ == "__main__":
    create_collect_item_table_if_not_exist()
    test_item = {'userid': 1,
                 'authorid': 1,
                 'cityid': 1,
                 'journeyid': 1}
    add_collect_item(test_item)
